<?php
if (!defined('IN_CORE')) die('禁止访问!');
	class page{
		private $now_page; 		//当前页
		private $page_rows;  // 每页显示条数
		private $total_rows;  // 总计
		private $total_page; // 总页数
		private $key;  		// GET的名称
		private $url;
		private $item=10;
		private $limit;    //SQL语句使用limit从名
		public function __construct($total_rows, $page_rows=10,$key='page'){
			$this->total_page = ceil($total_rows/$page_rows);
			$this->page_rows = $page_rows;
			$this->total_rows= $total_rows;
			$this->key= $key;
			$this->now_page =(isset($_GET[$key])&&$_GET[$key]>0) ? intval($_GET[$key]) : 1;
			$this->url = $this->getUrl();
			if($this->now_page > 0)
				$this->limit = ($this->page-1)*$this->page_rows.", {$this->page_rows}";
			else
				$this->limit = 0;
		}
		/**
		 * 获得 url 后面GET传递的参数
		 */ 
		public function getUrl(){   
			$url='/'.trim($GLOBALS['url'].core::$core_uri,'/').'/';
			$url = preg_replace('/(\/)?page\/(\w)+/','',$url);
			return $url.$this->key.'/';
		}
		/**
		 * 获得分页
		 */
		public function getPage(){
			$page='<ul class="pagination">';
			$page.="<li>共{$this->total_rows}条</li>";
			$page.="<li>{$this->now_page}/{$this->total_page}页</li>";
			$page.=$this->first();
			$page.=$this->prev();
			$page.=$this->pages();
			$page.=$this->next();
			$page.=$this->last();
			$page.='</ul>';
			return $page;
		}
		public function first(){
			return "<li><a href='{$this->url}1'>首页</a></li>";
		}
		public function last(){
			return "<li><a href='{$this->url}{$this->total_page}'>尾页</a></li>";
		}	
		public function prev(){
			$page=($this->now_page-1)>0?$this->now_page-1:1;
			return "<li><a href='{$this->url}{$page}'>上一页</a></li>";
		}
		public function next(){
			$page=($this->now_page+1)<$this->total_page?$this->now_page+1:$this->total_page;
			return "<li><a href='{$this->url}{$page}'>下一页</a></li>";
		}
		public function pages(){
			// $str='';
			// $inum=floor($this->item/2);
			// for($i=$inum; $i>0; $i--){
				// $page=$this->now_page-$i;
				// if($page>0){
					// $str.="<li><a href='{$this->url}{$page}'>{$page}</a></li>";
				// }
			// }
			// if($this->total_page > 1){
				// $str.="<li><span>{$this->now_page}</span></li>";
				// $str.='<br>';
			// }
			// for($i=1; $i<=$inum; $i++){
				// $page=$this->now_page+$i;
				// if($page<=$this->total_page)
					// $str.="<li><a href='{$this->url}{$page}'>{$page}</a></li>";
				// else break;
			// }
			$inum=floor($this->item/2);
			$start = $this->now_page-$inum;
			$start =($start>0)?$start:1;
			$end   = $start+$this->item;
			$str='';
			for($i=$start;$i<$end;$i++){
				if($i==$this->now_page){
					$str.="<li><span>{$this->now_page}</span></li>";
				}else if($i<=$this->total_page&&$i>0){
					$str.="<li><a href='{$this->url}{$i}'>{$i}</a></li>";
				}else{
					break;
				}
			}
			return $str;
		}
		function __get($args){
			if($args=="limit" || $args=="now_page")
				return $this->$args;
			else
				return null;
		}
	}